from rest_framework import serializers
from .models import address

class addressSerializer(serializers.ModelSerializer):
    address_info=serializers.CharField(read_only=True)
    class Meta:
        model = address
        fields = ['id','province','city','district','name','telephone','default','address','address_info']

    def validate(self, attrs):
        attrs['user']=self.context['user']
        # 如果前端传递的数据有isdefault字段，那么把其他的isdefault字段设置为False
        return attrs
    def update(self, instance, validated_data):
        if validated_data['default']:
            address.objects.filter(user=self.context['user']).update(default=False)
            instance.default = True
        instance=super(addressSerializer, self).update(instance, validated_data)
        instance.save()
        return instance
    def create(self, validated_data):
        if validated_data['default']:
            address.objects.filter(user=self.context['user']).update(default=False)
        instance=super(addressSerializer, self).create(validated_data)
        return instance
